﻿using ApplicationBase.Core.Context;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace Infrastructure.Core.Web.Controller
{
    #pragma warning disable CS8625
    public class BaseControllerActivator : ServiceBasedControllerActivator, IControllerActivator
    {
        object IControllerActivator.Create(ControllerContext context)
        {
            var instance = base.Create(context);
            if(instance is BaseController baseController)
            {
                var service = context.HttpContext.RequestServices;
                baseController.Mediator = service.GetService(typeof(IMediator)) as IMediator ?? throw new ArgumentNullException("Mediator unregistered.");
                baseController.ServiceContext = service.GetService(typeof(IServiceContext)) as IServiceContext ?? throw new ArgumentNullException("ServiceContext unregistered.");
            }
            return instance;
        }

        void IControllerActivator.Release(ControllerContext context, object controller)
        {
            base.Release(context, controller);
            var baseController = controller as BaseController;
            if(baseController != null)
            {
                baseController.Mediator = null;
                baseController.ServiceContext = null;
            }
        }
    }
}
